const { ccclass, property } = cc._decorator;
import { Player } from "../bean/Player";
import { Config } from "../bean/Config";
import { testData } from "../testData";
import { ToastUtils } from "../../../vv/utils/ToastUtils";
import { AudioUtil } from "../../../vv/utils/AudioUtil";
import { ResourceItemBean } from "../bean/ResourceItemBean";
import { gameEvents, resourcePath, EAudio } from "../../constants";

//游戏UI处理
@ccclass
export default class UiMain extends cc.Component {
    private centerNode: cc.Node = null; //主要用户交互UI界面
    private contentNode: cc.Node = null; //游戏逻辑节点

    //UI界面按钮组合
    private btnGroup: cc.Node = null;
    private top_bag_btn: cc.Node = null; //背包打开按钮
    private formulaBtn: cc.Node = null; //合成配方UI打开按钮
    private taskBtn: cc.Node = null; //任务UI打开按钮
    private worldBtn: cc.Node = null; //世界地图打开按钮
    private petBtn: cc.Node = null; //宠物打开按钮

    //进度条
    private loadingUI: cc.Node = null; //进度条UI
    private loadingPro: cc.ProgressBar = null; //进度条

    //背包系统
    private center_bag: cc.Node = null; //背包UI
    private center_bag_closeBtn: cc.Node = null; //背包关闭按钮
    private center_bag_itemLayout: cc.Node = null; //背包物品布局
    private destroyBtn: cc.Node = null; //背包物品销毁按钮
    private splitBtn: cc.Node = null; //背包物品拆分按钮
    private bagItemRemark: cc.Label = null; //背包物品描述文本

    //配方合成系统
    private formulaNode: cc.Node = null; //合成UI
    private formulaCloseBtn: cc.Node = null; //合成UI关闭按钮
    private formulaLayout: cc.Node = null; //配方布局
    private formulaMarkBtn: cc.Node = null; //制造
    private formulaDescLabel: cc.Label = null; //配方描述

    //玩家面板
    private playInfoNode: cc.Node = null;
    private playInfoHpPro: cc.ProgressBar = null; //体力条
    private playInfoHpProCurLabel: cc.Label = null; //体力条数值显示
    private playInfoExPro: cc.ProgressBar = null; //经验条
    private playInfoExProCurLabel: cc.Label = null; //经验条数值显示
    private playInfoLvLabel: cc.Label = null; //等级
    private playInfoCoinLabel: cc.Label = null; //金币

    //任务系统
    private taskNode: cc.Node = null; //任务UI
    private taskCloseBtn: cc.Node = null;
    private taskDescLabel: cc.Label = null;
    private taskLayout: cc.Node = null;

    //世界地图
    private worldMapNode: cc.Node = null; //任务UI
    private worldCloseBtn: cc.Node = null;
    private worldMap01Btn: cc.Node = null;
    private worldMap02Btn: cc.Node = null;

    //宠物
    private petNode: cc.Node = null;

    //动画特效
    private pickupAnimNode: cc.Node = null;

    protected onLoad() {
        this.initUI();
        this.onEvents();
    }

    protected start() {
        this.center_bag.active = false;
        this.loadingUI.active = false;
        this.bagItemRemark.string = "";
        this.formulaDescLabel.string = "";
        this.formulaNode.active = false;
        this.taskNode.active = false;
        this.taskDescLabel.string = "";
        this.worldMapNode.active = false;

        this.initConfig();
        this.initPlayInfo();
        this.initFormulaLayout();
        this.initTaskUI();
        this.initBagUI();
        this.initGame();
    }

    protected onDestroy() {
        this.offEvents();
    }

    //UI组件初始化
    private initUI() {
        this.contentNode = cc.find("Canvas/content");
        this.centerNode = cc.find("Canvas/ui/center");
        //合成配方
        this.formulaNode = this.centerNode.getChildByName("formula");
        this.formulaCloseBtn = this.formulaNode.getChildByName("closeFormulaBtn");
        this.formulaDescLabel = this.formulaNode.getChildByName("descLabel").getComponent(cc.Label);
        this.formulaLayout = this.formulaNode.getChildByName("ScrollView").getChildByName("view").getChildByName("content");
        this.formulaMarkBtn = this.formulaNode.getChildByName("btnGroup").getChildByName("markBtn");

        //任务
        this.taskNode = this.centerNode.getChildByName("task");
        this.taskCloseBtn = this.taskNode.getChildByName("closeBtn");
        this.taskDescLabel = this.taskNode.getChildByName("descLabel").getComponent(cc.Label);
        this.taskLayout = this.taskNode.getChildByName("ScrollView").getChildByName("view").getChildByName("content");

        //世界地图
        this.worldMapNode = this.centerNode.getChildByName("world");
        this.worldCloseBtn = this.worldMapNode.getChildByName("closeBtn");
        this.worldMap01Btn = this.worldMapNode.getChildByName("bg").getChildByName("map01");
        this.worldMap02Btn = this.worldMapNode.getChildByName("bg").getChildByName("map02");

        //宠物
        this.petNode = this.centerNode.getChildByName("pet");

        //界面按钮组
        this.btnGroup = cc.find("Canvas/ui/btnGroup");
        this.formulaBtn = this.btnGroup.getChildByName("formulaBtn");
        this.top_bag_btn = this.btnGroup.getChildByName("bagBtn");
        this.taskBtn = this.btnGroup.getChildByName("taskBtn");
        this.worldBtn = this.btnGroup.getChildByName("worldBtn");
        this.petBtn = this.btnGroup.getChildByName("petBtn");

        //背包
        this.center_bag = this.centerNode.getChildByName("bag");
        this.destroyBtn = this.center_bag.getChildByName("bomBtn").getChildByName("destroyBtn");
        this.splitBtn = this.center_bag.getChildByName("bomBtn").getChildByName("splitBtn");
        this.bagItemRemark = this.center_bag.getChildByName("itemRemark").getComponent(cc.Label);
        this.center_bag_itemLayout = this.center_bag.getChildByName("itemLayout");
        this.center_bag_closeBtn = this.center_bag.getChildByName("closeButton");
        //进度读条
        this.loadingUI = cc.find("Canvas/ui/loading");
        this.loadingPro = this.loadingUI.getChildByName("ProgressBar").getComponent(cc.ProgressBar);
        //玩家
        this.playInfoNode = cc.find("Canvas/ui/playInfo");
        this.playInfoHpPro = this.playInfoNode.getChildByName("hpProgressBar").getComponent(cc.ProgressBar);
        this.playInfoExPro = this.playInfoNode.getChildByName("exProgressBar").getComponent(cc.ProgressBar);
        this.playInfoHpProCurLabel = this.playInfoNode.getChildByName("hpProgressBar").getChildByName("curLabel").getComponent(cc.Label);
        this.playInfoExProCurLabel = this.playInfoNode.getChildByName("exProgressBar").getChildByName("curLabel").getComponent(cc.Label);
        this.playInfoLvLabel = this.playInfoNode.getChildByName("lvLabel").getComponent(cc.Label);
        this.playInfoCoinLabel = this.playInfoNode.getChildByName("coinLabel").getComponent(cc.Label);
        //拾取特效父节点
        this.pickupAnimNode = cc.find("Canvas/ui/pickupAnimNode");
    }

    //事件绑定
    private onEvents() {
        cc.director.on(gameEvents.onResourcePickup.toString(), this.onResourceItemPickup, this);
        cc.director.on(gameEvents.onLoading.toString(), this.onLoadingStart, this);
        cc.director.on(gameEvents.onBagItemClick.toString(), this.onBagItemClick, this);
        cc.director.on(gameEvents.onAddBagItem.toString(), this.onAddBagItem, this);
        cc.director.on(gameEvents.onAddPlayerHp.toString(), this.onAddPlayerHp, this);
        cc.director.on(gameEvents.onAddPlayerEx.toString(), this.onAddPlayerEx, this);
        cc.director.on(gameEvents.onFormulaItemClick.toString(), this.onFormulaItemClick, this);
        cc.director.on(gameEvents.onTaskItemClick.toString(), this.onTaskItemClick, this);

        this.center_bag_closeBtn.on(cc.Node.EventType.TOUCH_END, this.onbagCloseBtnClick, this);
        this.top_bag_btn.on(cc.Node.EventType.TOUCH_END, this.onBagBtnClick, this);
        this.destroyBtn.on(cc.Node.EventType.TOUCH_END, this.onDestroyBtnClick, this);
        this.splitBtn.on(cc.Node.EventType.TOUCH_END, this.onSplitBtnClick, this);
        this.formulaBtn.on(cc.Node.EventType.TOUCH_END, this.onMaterialsbtnClick, this);
        this.formulaCloseBtn.on(cc.Node.EventType.TOUCH_END, this.onMaterialsCloseBtnClick, this);
        this.formulaMarkBtn.on(cc.Node.EventType.TOUCH_END, this.onformulaMarkBtnClick, this);
        this.taskCloseBtn.on(cc.Node.EventType.TOUCH_END, this.onTaskCloseBtnClick, this);
        this.taskBtn.on(cc.Node.EventType.TOUCH_END, this.onTaskBtnClick, this);
        this.worldBtn.on(cc.Node.EventType.TOUCH_END, this.onWorldBtnClick, this);
        this.petBtn.on(cc.Node.EventType.TOUCH_END, this.onPetBtnClick, this);
        this.worldCloseBtn.on(cc.Node.EventType.TOUCH_END, this.onWorldCloseBtnClick, this);
        this.worldMap01Btn.on(cc.Node.EventType.TOUCH_END, this.onWorldMap01BtnClick, this);
        this.worldMap02Btn.on(cc.Node.EventType.TOUCH_END, this.onWorldMap02BtnClick, this);
    }

    //事件注销
    private offEvents() {
        cc.director.off(gameEvents.onResourcePickup.toString(), this.onResourceItemPickup, this);
        cc.director.off(gameEvents.onLoading.toString(), this.onLoadingStart, this);
        cc.director.off(gameEvents.onBagItemClick.toString(), this.onBagItemClick, this);
        cc.director.off(gameEvents.onAddBagItem.toString(), this.onAddBagItem, this);
        cc.director.off(gameEvents.onAddPlayerHp.toString(), this.onAddPlayerHp, this);
        cc.director.off(gameEvents.onAddPlayerEx.toString(), this.onAddPlayerEx, this);
        cc.director.off(gameEvents.onFormulaItemClick.toString(), this.onFormulaItemClick, this);
        cc.director.off(gameEvents.onTaskItemClick.toString(), this.onTaskItemClick, this);

        this.center_bag_closeBtn.off(cc.Node.EventType.TOUCH_END, this.onbagCloseBtnClick, this);
        this.top_bag_btn.off(cc.Node.EventType.TOUCH_END, this.onBagBtnClick, this);
        this.destroyBtn.off(cc.Node.EventType.TOUCH_END, this.onDestroyBtnClick, this);
        this.splitBtn.off(cc.Node.EventType.TOUCH_END, this.onSplitBtnClick, this);
        this.formulaBtn.off(cc.Node.EventType.TOUCH_END, this.onMaterialsbtnClick, this);
        this.formulaCloseBtn.off(cc.Node.EventType.TOUCH_END, this.onMaterialsCloseBtnClick, this);
        this.formulaMarkBtn.off(cc.Node.EventType.TOUCH_END, this.onformulaMarkBtnClick, this);
        this.taskCloseBtn.off(cc.Node.EventType.TOUCH_END, this.onTaskCloseBtnClick, this);
        this.taskBtn.off(cc.Node.EventType.TOUCH_END, this.onTaskBtnClick, this);
        this.worldBtn.off(cc.Node.EventType.TOUCH_END, this.onWorldBtnClick, this);
        this.petBtn.off(cc.Node.EventType.TOUCH_END, this.onPetBtnClick, this);
        this.worldCloseBtn.off(cc.Node.EventType.TOUCH_END, this.onWorldCloseBtnClick, this);
        this.worldMap01Btn.off(cc.Node.EventType.TOUCH_END, this.onWorldMap01BtnClick, this);
        this.worldMap02Btn.off(cc.Node.EventType.TOUCH_END, this.onWorldMap02BtnClick, this);
    }

    //初始化游戏全局配置数据
    private initConfig() {
        let value = testData.getConfigData();
        Config.inst.init(value.hpConsumeRate, value.exGrowRate, value.cHpConsumeRate, value.cExGrowRate);
        Config.inst.weather = value.weather;
        Config.inst.season = value.season;
        Config.inst.setCache();
    }

    //初始化玩家信息
    private initPlayInfo() {
        let play = testData.getPlayInfo();
        Player.inst.init(play.hp, play.maxHp, play.ex, play.maxEx, play.lv, play.coin);
        Player.inst.token = "1";
        Player.inst.setCache();

        this.updatePlayInfoHpPro(play.hp, play.maxHp);
        this.updatePlayInfoExPro(play.ex, play.maxEx);
        this.playInfoLvLabel.string = play.lv + "";
        this.playInfoCoinLabel.string = play.coin + "";
    }

    //初始化游戏逻辑
    private initGame() {
        let script = this.contentNode.getComponent("gameContent");
        script.initResourceItemPool();
    }

    //更新体力值UI
    private updatePlayInfoHpPro(cur: number, max: number) {
        let rate = "0";
        if (Number(cur) > 0) {
            rate = (cur / max).toFixed(2);
        }
        this.playInfoHpPro.progress = Number(rate);
        this.playInfoHpProCurLabel.string = cur + "/" + max;
    }

    //更新经验值UI
    private updatePlayInfoExPro(cur: number, max: number) {
        let rate = "0";
        if (Number(cur) > 0) {
            rate = (cur / max).toFixed(2);
        }
        this.playInfoExPro.progress = Number(rate);
        this.playInfoExProCurLabel.string = cur + "/" + max;
    }

    private onAddPlayerHp(cur: number, max?: number) {
        cur = cur + Player.inst.hp;
        Player.inst.hp = cur;
        if (!max) {
            max = Player.inst.maxHp;
            Player.inst.maxHp = max;
        }
        Player.inst.setCache();
        this.updatePlayInfoHpPro(cur, max);
    }

    private onAddPlayerEx(cur: number, max?: number) {
        cur = cur + Player.inst.ex;
        Player.inst.ex = cur;
        if (!max) {
            max = Player.inst.maxEx;
            Player.inst.maxEx = max;
        }
        Player.inst.setCache();
        this.updatePlayInfoExPro(cur, max);
    }

    //背包按钮
    private onBagBtnClick() {
        for (let item of this.centerNode.children) {
            if (item.name != this.center_bag.name) {
                item.active = false;
            }
        }
        this.center_bag.active = !this.center_bag.active;
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
    }

    //关闭背包
    private onbagCloseBtnClick() {
        this.center_bag.active = false;
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
    }

    //打开合成技能UI
    private onMaterialsbtnClick() {
        for (let item of this.centerNode.children) {
            if (item.name != this.formulaNode.name) {
                item.active = false;
            }
        }
        this.formulaNode.active = !this.formulaNode.active;
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
    }

    //配方技能被选中事件
    private onFormulaItemClick(obj: cc.Node) {
        let script = obj.getComponent("formulaItem");
        let desc = script.desc;
        this.formulaDescLabel.string = desc;
    }

    private onMaterialsCloseBtnClick() {
        this.formulaNode.active = false;
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
    }

    private onAddBagItem(itemId: string, count: number, remark: string, itype: number) {
        this.addBagItem(itemId, count, remark, itype);
    }

    //物品拾取事件
    private async onResourceItemPickup(itemNode: cc.Node) {
        if (this.loadingUI.active == true) {
            ToastUtils.show("物品现在还不能拾取");
            return;
        }
        let resourceItem = itemNode.getComponent("resourceItem");
        let remark = resourceItem.remark;
        let itemId = resourceItem.itemId;
        let count = resourceItem.count;
        let lv = resourceItem.lv;
        let mapId = resourceItem.mapId;
        let rowId = resourceItem.rowId;
        vv.log("[物品" + itemId + "被拾取，数量=" + count + "，描述=" + remark + "]");
        await this.onLoadingStart();
        let p = Config.inst.isProductionFailed(lv);
        if (p == 0) {
            //TODO 播放成功音效
            AudioUtil.inst.playEffect(EAudio.PickUp);
            //特效
            let startPos = this.getCanvasSpacePos(itemNode);
            let endPos = this.getCanvasSpacePos(this.top_bag_btn);

            this.getPickupEffects(startPos, endPos, count);

            itemNode.destroy(); //删除该地图资源
            //放入背包
            this.addBagItem(itemId, count, remark);
            //加经验
            this.onAddPlayerEx(Config.inst.getExGrow(lv));
            //减体力
            this.onAddPlayerHp(-Config.inst.getHpConsume(lv));
            //设置缓存
            ResourceItemBean.inst.removeResource(mapId, rowId);
            //TODO 同步服务器
        } else {
            //TODO 播放失败音效
            AudioUtil.inst.playEffect(EAudio.PFailure);
            //减体力
            this.onAddPlayerHp(-p);
            ToastUtils.show("采集失败");
            //TODO 同步服务器
        }
    }

    //添加物品到背包
    private addBagItem(itemId: string, count: number, remark: string, itype: number = 0) {
        //先判断背包是否已存在该物品，如存在则叠加，否则加入新的
        for (let i = 0; i < this.center_bag_itemLayout.children.length; i++) {
            let item = this.center_bag_itemLayout.children[i].getComponent("bagItem");
            if (parseInt(item.itemId) == parseInt(itemId)) {
                //已存在则叠加数量
                item.addItemCount(count);
                return;
            }
        }

        cc.resources.load(resourcePath.bagItemPrefab, cc.Prefab, (err, prefab: any) => {
            let item = cc.instantiate(prefab);
            this.center_bag_itemLayout.addChild(item);
            //要先加入场景中触发onLoad后
            item.getComponent("bagItem").init(itemId, count, remark, itype);
        });
    }

    //拾取特效
    private getPickupEffects(startPos: cc.Vec2, endPos: cc.Vec2, count: number) {
        let startPoints: cc.Vec2[] = [];
        for (let index = 0; index < count; index++) {
            startPoints.push(startPos);
        }

        let points = this.getCirclePoints(startPos, count);
        cc.resources.load(resourcePath.pickupEffectsPrefab, cc.Prefab, (err, prefab: any) => {
            let efNodeList = points.map((pos) => {
                let efNode = cc.instantiate(prefab);
                efNode.setPosition(startPos);
                this.pickupAnimNode.addChild(efNode);
                return {
                    node: efNode,
                    stPos: startPos,
                    mdPos: pos,
                    edPos: endPos,
                    dis: (pos as any).sub(endPos).mag(),
                };
            });
            efNodeList = efNodeList.sort((a, b) => {
                if (a.dis - b.dis > 0) return 1;
                if (a.dis - b.dis < 0) return -1;
                return 0;
            });

            efNodeList.forEach((item, i) => {
                item.node.runAction(
                    cc.sequence(
                        cc.moveTo(0.3, item.mdPos),
                        cc.delayTime(i * 0.03),
                        cc.moveTo(1, endPos),
                        cc.callFunc(() => {
                            item.node.destroy();
                        })
                    )
                );
            });
        });
    }

    /**
     * 以某点为圆心，生成圆周上等分点的坐标
     *
     * @param {number} r 半径
     * @param {cc.Vec2} pos 圆心坐标
     * @param {number} count 等分点数量
     * @param {number} [randomScope=80] 等分点的随机波动范围
     * @returns {cc.Vec2[]} 返回等分点坐标
     */
    private getCirclePoints(pos: cc.Vec2, count: number, r: number = 60, randomScope: number = 30): cc.Vec2[] {
        let points = [];
        let radians = (Math.PI / 180) * Math.round(360 / count);
        for (let i = 0; i < count; i++) {
            let x = pos.x + r * Math.sin(radians * i);
            let y = pos.y + r * Math.cos(radians * i);
            points.unshift(cc.v3(x + Math.random() * randomScope, y + Math.random() * randomScope, 0));
        }
        return points;
    }

    //获取节点在屏幕上的坐标
    private getCanvasSpacePos(node: cc.Node) {
        return cc.v2(cc.Canvas.instance.node.convertToNodeSpaceAR(node.convertToWorldSpaceAR(cc.v2(0, 0))));
    }

    //进度条事件
    private async onLoadingStart(time: number = 1.5) {
        if (this.loadingUI.active == false) {
            this.loadingUI.active = true;
        }
        return new Promise((resolve, reject) => {
            cc.tween(this.loadingPro)
                .to(
                    time,
                    { progress: 1 },
                    {
                        progress: (start, end, current, ratio) => {
                            let num = start + (end - start) * ratio;
                            // this.labelProgress.string = `${Math.floor(num * 100)}%`;//进度百分比文本显示
                            return num;
                        },
                    }
                )
                .call(() => {
                    //动画完成回调
                    this.loadingPro.progress = 0;
                    this.loadingUI.active = false;
                    resolve();
                })
                .start();
        });
    }

    //销毁选中的背包物品
    private onDestroyBtnClick() {
        vv.log("[点击销毁]");
        for (let i = 0; i < this.center_bag_itemLayout.children.length; i++) {
            if (this.center_bag_itemLayout.children[i].getComponent("bagItem").isSelected == true) {
                this.center_bag_itemLayout.children[i].destroy();
                break;
            }
        }
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
    }

    //通过物品ID销毁背包物品或扣减数量
    private destroyBagItem(itemId: string | number, count: number) {
        for (let i = 0; i < this.center_bag_itemLayout.children.length; i++) {
            let item = this.center_bag_itemLayout.children[i].getComponent("bagItem");
            if (item.itemId == itemId) {
                if (Number(item.itemCount) > count) {
                    //扣减数量
                    item.addItemCount(-count);
                } else {
                    //相等或不足则直接删除
                    this.center_bag_itemLayout.children[i].destroy();
                }
                break;
            }
        }
    }

    //背包物品进行合成
    private async onSynthesis(id: number) {
        if (this.loadingUI.active == true) {
            ToastUtils.show("现在还不能操作");
            return;
        }
        if (id == null) {
            vv.log("[id不存在]");
            return;
        }

        let formulaData = testData.getFormulaDataById(id); //测试数据
        if (formulaData == null) {
            vv.log("[配方不存在]");
            return;
        }

        //寻找是否存在符合公式的物品
        let isEx: boolean = false;
        let count: number = 0;
        for (let formula of formulaData.materials) {
            isEx = false;
            count = 0;
            for (let i = 0; i < this.center_bag_itemLayout.children.length; i++) {
                let item = this.center_bag_itemLayout.children[i].getComponent("bagItem");
                if (item.itemId == formula.itemId) {
                    isEx = true;
                    count = count + Number(item.itemCount);
                }
            }
            if (isEx == false) {
                ToastUtils.show("材料不足");
                vv.log("[材料不足，缺少物品：" + formula.itemId + "]");
                return;
            } else if (count < formula.count) {
                ToastUtils.show("材料不足");
                vv.log("[材料不足，缺少物品数量：" + formula.itemId + "]");
                return;
            }
        }

        await this.onLoadingStart();

        let lv = formulaData.lv;
        let p = Config.inst.isCompoundFailed(lv);
        if (p == 0) {
            //TODO 播放成功音效
            AudioUtil.inst.playEffect(EAudio.PickUp);

            //加经验
            this.onAddPlayerEx(Config.inst.getExGrow(lv, true));
            //减体力
            this.onAddPlayerHp(-Config.inst.getHpConsume(lv, true));
            //设置缓存

            //合成成品并销毁材料
            for (let formula of formulaData.materials) {
                this.destroyBagItem(formula.itemId, formula.count);
            }
            this.addBagItem(formulaData.productId, formulaData.productCount, formulaData.productRemark, formulaData.itype);
            //TODO 同步服务器
        } else {
            ToastUtils.show("合成失败");
            AudioUtil.inst.playEffect(EAudio.PFailure);

            //TODO 同步服务器
        }
    }

    //背包物品拆分
    private onSplitBtnClick() {
        vv.log("[点击拆分]");
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
    }

    //背包物品被点击
    private onBagItemClick(itemNode: cc.Node) {
        let bagItem = itemNode.getComponent("bagItem");
        let remark = bagItem.remark;
        this.bagItemRemark.string = remark;
    }

    //初始化背包UI
    private initBagUI() {
        let data = testData.getBagData();

        for (let item of data) {
            this.addBagItem(item.id, item.count, item.desc);
        }
    }

    //初始化配方UI
    private initFormulaLayout() {
        let data = testData.getFormulaData();

        cc.resources.load(resourcePath.formulaItemPrefab, cc.Prefab, (err, prefab: any) => {
            for (let item of data) {
                let node = cc.instantiate(prefab);
                this.formulaLayout.addChild(node);
                node.getComponent("formulaItem").init(item.id, item.lv, item.title, item.desc, item.count, item.itype);
            }
        });
    }

    //制作
    private onformulaMarkBtnClick() {
        let id = null;
        //查询当前选中的配方
        for (let i = 0; i < this.formulaLayout.children.length; i++) {
            if (this.formulaLayout.children[i].getComponent("formulaItem").isSelected == true) {
                id = this.formulaLayout.children[i].getComponent("formulaItem").formulaId;
                break;
            }
        }
        this.onSynthesis(id);
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
    }

    private onTaskCloseBtnClick() {
        this.taskNode.active = false;
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
    }

    private onTaskBtnClick() {
        for (let item of this.centerNode.children) {
            if (item.name != this.taskNode.name) {
                item.active = false;
            }
        }
        this.taskNode.active = !this.taskNode.active;
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
    }

    //任务被选中事件
    private onTaskItemClick(obj: cc.Node) {
        let script = obj.getComponent("taskItem");
        let desc = script.desc;
        this.taskDescLabel.string = desc;
    }

    //初始化任务
    private initTaskUI() {
        let data = testData.getTaskData();

        cc.resources.load(resourcePath.taskItemPrefab, cc.Prefab, (err, prefab: any) => {
            for (let item of data) {
                let node = cc.instantiate(prefab);
                this.taskLayout.addChild(node);
                node.getComponent("taskItem").init(item.id, item.state, item.title, item.desc);
            }
        });
    }

    private onPetBtnClick() {
        for (let item of this.centerNode.children) {
            if (item.name != this.petNode.name) {
                item.active = false;
            }
        }
        this.petNode.active = !this.petNode.active;
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
    }

    //打开或关闭世界地图
    private onWorldBtnClick() {
        for (let item of this.centerNode.children) {
            if (item.name != this.worldMapNode.name) {
                item.active = false;
            }
        }
        this.worldMapNode.active = !this.worldMapNode.active;
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
    }

    private onWorldCloseBtnClick() {
        this.worldMapNode.active = false;
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
    }

    //世界地图切换，地图2被点击
    private onWorldMap02BtnClick() {
        vv.getScript(this.contentNode).resetResourceItem(2);
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
        this.worldMapNode.active = false;
    }
    private onWorldMap01BtnClick() {
        vv.getScript(this.contentNode).resetResourceItem(1);
        AudioUtil.inst.playEffect(EAudio.E_CLICK);
        this.worldMapNode.active = false;
    }

    //使用物品
    private useBagGoods() {}

    //出售物品
    private sellBagGoods(id: number, count: number) {
        //TODO 出售前显示出售价格，进行出售加钱

        this.destroyBagItem(id, count);
    }

    /**
     * 拍卖物品
     * @param id 要拍卖的物品ID
     * @param count 物品数量
     * @param price 拍卖单价
     * @param time 拍卖最大时间 最大48 最小3
     */
    private auctionBagGoods(id: number, count: number, price: number, time: number) {
        let charge = count * price * 0.05; //手续费

        //TODO 将背包物品转移到拍卖行

        this.destroyBagItem(id, count);
    }
}
